﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebLayer;
using HtmlAgilityPack;
using System.Globalization;

namespace WebPageParser
{
    class LevelAndUnitPage: SiteWebPage 
    {
        public static readonly Uri WelcomePageUri = new Uri(@"http://sz.speak-up.com.ua/StrefaSluchacza/index.php");

        public LevelAndUnitPage() :
        base("Welcome", WelcomePageUri)
        {}

        public int Level { get; private set; }
        public int Unit { get; private set; } 

        protected override void OnResponse(System.Net.HttpWebRequest request, System.Net.HttpWebResponse response)
        {
            base.OnResponse(request, response);

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(PageContent);

            //Course html page has only one table. Select it;
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@id='m_header']/div[1]");

            string text = node.InnerText;
            string LevelPattern = "Level: ";
            string UnitPattern = "Unit: ";
            int levelIdx = text.IndexOf(LevelPattern);
            int unitIdx  = text.IndexOf(UnitPattern);

            if (levelIdx < 0 || unitIdx < 0)
            {
                throw new FormatException("Level or Unit string is not found in welcome web page.");
            }

            int levelEndIdx = text.IndexOf('\n', levelIdx);
            int unitEndIdx = text.IndexOf('\n', unitIdx);

            if (levelEndIdx < 0 || unitEndIdx < 0)
            {
                throw new FormatException("Level or Unit string is not found in welcome web page.");
            }

            string levelStr = text.Substring(levelIdx + LevelPattern.Length, levelEndIdx - levelIdx - LevelPattern.Length);
            string unitStr = text.Substring(unitIdx + UnitPattern.Length, unitEndIdx - unitIdx - UnitPattern.Length);
            Level = Int32.Parse(levelStr, NumberStyles.Number );
            Unit = Int32.Parse(unitStr, NumberStyles.Number);

        }
    }
}
